/*
 * WorxXMLRequest.java
 *
 * Created Apr 27, 2006
 * David Connell
 * Copyright (c) 2005 Synergy Systems, Inc
 */
package org.puresilk.afx.util;

import java.net.HttpURLConnection;
import java.net.URL;

import org.jdom.Document;
import org.jdom.input.SAXBuilder;
import org.puresilk.afx.SilkAfxException;

/**
 * Utility to retrieve a chunk of XML from another 
 * server.  Initially intended to link into AuthWorx 
 * from AdminWorx, this object was generalized to
 * handle most any cross domain calls.
 * 
 * WARNING:  Use of this class requires the JDOM
 * classes (www.jdom.org) to be available.  The
 * jdom.jar should be placed in the WEB-INF/lib
 * directory of the WAR file. 
 *
 */
public class SilkAfxXMLRequest{
	private String _url = null;
	private String _data = null;
	
	
	public static Document getResponse(String url, String data)  throws SilkAfxException {
		SilkAfxXMLRequest wxr = new SilkAfxXMLRequest(url,data);
		return wxr.getResponse();
	}
		
	public SilkAfxXMLRequest(String url, String data) {
		_url = url;
		_data = data;
	}
	
	public Document getResponse() throws SilkAfxException {
		Document dom = null;
		try {
			// prepare the request
			URL reqUrl = new URL(_url);
			
			// get the connection
			HttpURLConnection uc = (HttpURLConnection)reqUrl.openConnection();
			uc.setRequestMethod("POST");
			uc.setDoOutput(true);
			uc.setRequestProperty("Content-length",Integer.toString(_data.length()));
			uc.connect();
			
			// send output
			uc.getOutputStream().write(_data.getBytes());
			
			// get and parse response
			SAXBuilder parser = new SAXBuilder();
			dom = parser.build(uc.getInputStream());
			
			// done with network
			uc.disconnect();
		}
		catch(Exception ex) {
			throw new SilkAfxException(ex);
		}
		
		// send back the parsed DOM
		return dom;
	}	

	public String get_data() {
		return _data;
	}

	public void set_data(String _data) {
		this._data = _data;
	}

	public String get_url() {
		return _url;
	}

	public void set_url(String _url) {
		this._url = _url;
	}
}